/**
 * @author edwin
 * @email edwin.zhao@nike.com
 * @date 2019-07-04
*/
package com.longge.bigfile.config;

import java.util.HashMap;
import java.util.Map;

import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import com.aliyun.oss.OSS;
import com.aliyun.oss.OSSClientBuilder;
import com.longge.bigfile.service.ProcessService;
import com.longge.bigfile.service.impl.OSSProcessServiceImpl;
import com.longge.bigfile.util.OSSClientUtils;

import lombok.Getter;
import lombok.Setter;

/**
 * 
 * @author roger yang
 * @date 11/04/2019
 */
@Configuration
@ConditionalOnProperty(name="bigfile.storageType", havingValue="oss", matchIfMissing=true)
public class OSSConfiguration {
	
	@Bean
	public OSSClientBootstrap ossClientBootstrap(OSSMulitiConfig configs) {
		Map<String, OSS> ossClients = new HashMap<>();
	    Map<String, OSSConfig> ossConfigs = new HashMap<>();
	    
	    configs.getProjects().entrySet().forEach(entry -> {
	    	OSSConfig config = entry.getValue();
	    	OSS ossClient = new OSSClientBuilder().build(config.getEndpoint(), config.getAccessKeyId(), config.getSecretAccessKey());
	        
	    	ossConfigs.put(entry.getKey(), config);
	    	ossClients.put(entry.getKey(), ossClient);
	    });
	    OSSClientUtils.setOssClients(ossClients);
	    OSSClientUtils.setOssConfigs(ossConfigs);
		return null;
	}
	
	@Bean
	public ProcessService ossService() {
		return new OSSProcessServiceImpl();
	}
	
	@Configuration
	@ConfigurationProperties(prefix = "oss")
	@Getter
	@Setter
	public static class OSSMulitiConfig {
	    private Map<String, OSSConfig> projects;
	}
	
	@Getter
	@Setter
	public static class OSSConfig {
	    private String bucketName;
	    
	    private String accessKeyId;
	    
	    private String secretAccessKey;
	    
	    private String endpoint;
	}
	
	static class OSSClientBootstrap {}
}
